import { version } from '../package.json'

export interface JSDispatchParams {
    timer?: number
    step?: number
    flag?: boolean
}

export default class JSDispatch {

    private timer = -1
    private step = 250
    private flag = false

    constructor(params: JSDispatchParams) {
        const { timer = -1, step = 250, flag = false } = params || {};
        this.timer = timer;
        this.step = Math.abs(step);
        this.flag = Boolean(flag)
    }

    debounce(task: Function): void {
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
            try {
                task && task()
            } catch (error) {
                console.error(error)
            }
        }, this.step)
    }

    throttle(task: Function): void {
        if (!this.flag && task) {
            this.flag = true
            try {
                task(() => {
                    this.flag = false;
                })
            } catch (error) {
                console.error(error)
                this.flag = false;
            }
        }
    }

    static version = version
}
